package hotel.controller;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import hotel.entity.Bed;
import hotel.service.IBedService;
import util.JSONUtil;

@Controller
public class BedController {
	//Jackson
	private final static ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private IBedService<Bed> bedService;
	
	@RequestMapping(value="bedManagement")
	public String bedManagement() {
		return "bed/bedlist";
	}
	
	@ResponseBody
	@RequestMapping(value = "bedlist")
	public String getBedList(Model model) {
		String json=null;
		try {
			json=mapper.writeValueAsString(bedService.listAll("Bed"));
			json="{\"data\":"+json+"}";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value="addBed",method=RequestMethod.GET)
	public String add() {
		return "bed/add";
	}
		
	@ResponseBody
	@RequestMapping(value="addBed",method=RequestMethod.POST)
	public String addBed(Bed bed) {
		if(bedService.save(bed))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
		
	@RequestMapping(value="editBed",method=RequestMethod.GET)
	public String edit(int bedid,Model model) {
		model.addAttribute("bed", bedService.findById(Bed.class, bedid));
		return "bed/edit";
	}
		
	@ResponseBody
	@RequestMapping(value="editBed",method=RequestMethod.POST)
	public String editBed(Bed bed) {
		if(bedService.update(bed))
			return JSONUtil.returnSuccess();
		return JSONUtil.returnFailure();
	}
		
	@ResponseBody
	@RequestMapping(value="deleteBed")
	public String deleteBed(int bedid) {
		if(bedService.deleteById("Bed", bedid))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
}
